package com.dz.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().
                antMatchers("/").permitAll()   //任何人都可以访问首页
                .antMatchers("/level1/**").hasRole("vip1") //vip1等级的可以访问level1
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //没有权限，默认回到登录页面
        http.formLogin();
        //注销成功后 返回首页 而不是登录页面
//        http.logout();
        http.logout().logoutSuccessUrl("/");
//        实现记住我功能
//        http.rememberMe();
//        实现自定义的记住我功能
        http.rememberMe().rememberMeParameter("remember");
    }
   //认证
    @Override    //passwordEncoder(new BCryptPasswordEncoder()) 对密码进行加密，否则会报错
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //下边的数据应该从数据库中获取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("dz").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("zsq").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
